package cn.xspace.module.other.fragment;

import android.content.ClipData;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.xspace.android.xafcommon.appliction.BaseAppliction;
import com.xspace.android.xafcommon.base.BaseFragment;
import com.xspace.android.xafcommon.util.Constants;
import com.xspace.android.xafcommon.util.ExpUtils;
import com.xspace.android.xafcommon.util.LogUtil;
import com.xspace.android.xafcommon.util.Navigation;
import com.xspace.android.xafcommon.util.PreferencesUtils;
import com.xspace.android.xafcommon.util.RequestConstant;
import com.xspace.android.xafcommon.util.ResourceUtils;
import com.xspace.android.xafcommon.util.T;
import com.xspace.android.xafcommon.view.DialogSetTextSize;
import com.xspace.android.xafcommon.view.dialog.ButtonClickListener;
import com.xspace.android.xafcommon.view.dialog.WebViewMoreDialog;
import com.xspace.android.xafcommon.view.rsv.RangeSliderView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

import cn.xspace.app.view.TitleBar;
import cn.xspace.library.bean.Type;
import cn.xspace.library.util.BldNavigation;
import cn.xspace.library.util.MsgType;
import cn.xspace.library.util.MyInfoUtil;
import cn.xspace.library.util.Tools;
import cn.xspace.module.other.R;


public class WnxWebViewFragment extends BaseFragment {

    private static final String TAG = WnxWebViewFragment.class.getSimpleName();
    public static final String PARAM_CONTENT = "param_content";

    private TitleBar mTitleBar;
    private WebView webView;

    private String tempUrl;
    private int type = -1;
    private String mUrl = "";
    private String mTitle = "";
    private String mContent = "";
    private String org_id = "";
    private String m_Web_Title = "";
    private String msg_deptid = "";
    private boolean showCollection = true; //是否显示收藏.默认显示
    private boolean showMore = true; //是否显示右上角更过按钮,末日呢显示


    private WebViewMoreDialog dialog;
    private DialogSetTextSize.Builder setTextSize;

    private String WEB_VIEW_INDEX = "webViewIndex";
    private int index;
    private int tempIndex;
    private boolean isInnerShowTitle = false;
    //    public static final String PARAM_WEB_URL = "param_web_url";
//    public static final String PARAM_TITLE = "param_title";
//    private TextView title;
//    public RelativeLayout rl_set;
//    private UmengUtil mUmengUtil;
//    private Dialog dialog;
    private String[] titleArray;

    public static WnxWebViewFragment newInstance(Bundle bundle) {
        WnxWebViewFragment fragment = new WnxWebViewFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    public void onResume() {
        super.onResume();
        webView.onResume();
    }

    public void onPause() {
        super.onPause();
        webView.onPause();
    }

    @Override
    public void initData() {
        titleArray = ResourceUtils.getStringArray(R.array.more_groups);
        SharedPreferences share = BaseAppliction.mInstance.getSharedPreferences(PreferencesUtils.SpName, Context
                .MODE_PRIVATE);
        index = share.getInt(WEB_VIEW_INDEX, 2);
        LogUtil.d("wubaojie>>>initDatas: " + index);
        webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        webView.setHorizontalScrollBarEnabled(false);
        WebSettings settings = webView.getSettings();
        settings.setAllowFileAccess(true);
        settings.setJavaScriptEnabled(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setLoadsImagesAutomatically(true);
        settings.setSupportZoom(true);
        settings.setTextZoom(50 + index * 25);
        settings.setBlockNetworkImage(false);
        webView.setWebChromeClient(wcc);
        webView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    if (webView.canGoBack()) {
                        webView.goBack();
                        return true;
                    } else {
                        return false;
                    }
                }
                return false;
            }
        });
        webView.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // if (url.indexOf(".doc") > 0 || url.indexOf(".pdf") > 0
                // || url.indexOf(".xls") > 0 || url.indexOf(".ppt") > 0
                // || url.indexOf(".wps") > 0 || url.indexOf(".et") > 0
                // || url.indexOf(".dps") > 0) {
                // Uri uri = Uri.parse(url);
                // Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                // startActivity(intent);
                //
                // } else {
                view.loadUrl(url);
                // }
                return true;
            }

            @Override
            public void onPageFinished(final WebView view, String url) {
                super.onPageFinished(view, url);

                LogUtil.d(" view Cangoback" + view.canGoBack());
                LogUtil.d(" webView Cangoback" + webView.canGoBack());
//                if (!isShowBack) {
//                if(!isShowBack){
//
//                }
                if (view.canGoBack() || webView.canGoBack()) {
                    if (isInnerShowTitle) {
                        mTitleBar.setTitle(view.getTitle());
                    } else {
                        mTitleBar.setTitle("资讯详情");
                    }
                    mTitleBar.setLeftLayoutVisibility(View.VISIBLE);
                } else {
                    if (!isShowBack) {
                        mTitleBar.setLeftLayoutVisibility(View.GONE);
                    } else {
                        mTitleBar.setLeftLayoutVisibility(View.VISIBLE);
                    }
                    if (TextUtils.isEmpty(mTitle)) {
                        if(isInnerShowTitle){
                            mTitleBar.setTitle(view.getTitle());
                        }else{
                            mTitleBar.setTitle("资讯详情");
                        }
                    } else {
                        mTitleBar.setTitle(mTitle);
                    }
                }
//                } else {
//
//                }
                m_Web_Title = view.getTitle();
//                if (TextUtils.isEmpty(mTitle)) {
//                    String title = view.getTitle();
//                    if (!TextUtils.isEmpty(title) && !(title.endsWith(".html") || title.endsWith(".htm"))) {
//                        mTitle = title;
//                        m_Web_Title = title;
//                    }
//                }
                volleyGetShortUrl(mUrl);
                Log.i("wnx", "onPageFinished PlatformWebViewAct m_Web_Title:" + m_Web_Title);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                webView.loadUrl("file:///android_asset/index.html");
            }

        });

        if (tempUrl == null || Uri.parse(tempUrl) == null) {
            webView.loadUrl("file:///android_asset/index.html");
        } else {
            mUrl = tempUrl;
            if (mUrl.contains("?")) {
                mUrl += "&userid=" + Tools.getCurrentAccountInfo(mContext).uuid;
            } else {
                mUrl += "?userid=" + Tools.getCurrentAccountInfo(mContext).uuid;
            }
            webView.loadUrl(mUrl);
        }
    }

    protected void getIntentData() {
        super.getIntentData();
        if (fragmentArgs != null) {
            tempUrl = fragmentArgs.getString(Constants.WEBVIEURL);
            type = fragmentArgs.getInt("type", -1);
            showCollection = fragmentArgs.getBoolean("Collection", true); //是否显示收藏,默认显示
            showMore = fragmentArgs.getBoolean("showMore", true); //是否显示收藏,默认显示
            mTitle = fragmentArgs.getString(Constants.TITITL);
            mContent = fragmentArgs.getString(PARAM_CONTENT);
            org_id = fragmentArgs.getString(RequestConstant.KEY_ORG_ID);
            if (TextUtils.isEmpty(org_id)) {
                org_id = MyInfoUtil.getAppOrgId();
            }
            //收藏时使用,微农信收藏时将org_id赋值给depid,用于查询机构时使用
            msg_deptid = org_id; //从收藏夹进入时无法在点击收藏,不需要传递该字段了
            LogUtil.d(TAG, "wubaojie>>>getIntentData: mTitle :" + mTitle + " mContent:" + mContent + " type : " + type +
                    " tempUrl:" + tempUrl);

            Map<String, String> stringStringMap = ExpUtils.urlSplit(tempUrl);
            if (stringStringMap.containsKey("browserType") && "showTitle".equals(stringStringMap.get("browserType"))) {
                isInnerShowTitle = true;
            }
            if (stringStringMap.containsKey("hideMenu") && "1".equals(stringStringMap.get("hideMenu"))) {
                showMore = false;
            }

        }

    }


    @Override
    protected void initEvent() {
        mTitleBar.setRightLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    showMoreDialog();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
//        mTitleBar.setLeftLayoutClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                exitActivity();
//            }
//        });

        mTitleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (webView.canGoBack()) {
                    webView.goBack();
                } else {
                    exitActivity();
                }
            }
        });

        if (isShowTop) {
            if (!isShowBack) {
                mTitleBar.setLeftLayoutVisibility(View.GONE);
            } else {
                mTitleBar.setLeftLayoutVisibility(View.VISIBLE);
            }

            if (TextUtils.isEmpty(mTitle)) {
                if(!isInnerShowTitle){
                    mTitleBar.setTitle("资讯详情");
                }
            } else {
                mTitleBar.setTitle(mTitle);
            }
        } else {
            mTitleBar.setVisibility(View.GONE);
        }

    }

    @Override
    public View initView(LayoutInflater inflater) {

        return inflater.inflate(R.layout.web_view_activity, null);
    }

    @Override
    protected void initFindViewById(View view) {
        mTitleBar = (TitleBar) view.findViewById(R.id.web_view_title);
        if (!showMore) {
            mTitleBar.setRightLayoutVisibility(View.GONE);
        }
        mTitleBar.setRightImageResource(R.drawable.icon_function_more);
        webView = (WebView) view.findViewById(R.id.web_webview);
    }

    private void showMoreDialog() {
        if (dialog != null && dialog.isShowing()) {
            return;
        }
        if (dialog == null) {

            final String[] titles;
            if (type == MsgType.NOTICE.toNumber()) { //通知公告显示内容
                if (showCollection) {
                    titles = new String[]{"收藏", "查看机构", "调整字号", "刷新"};
                    dialog = new WebViewMoreDialog.Builder(mContext, titles).build();
                } else {
                    titles = new String[]{"查看机构", "调整字号", "刷新"};
                    dialog = new WebViewMoreDialog.Builder(mContext, titles).build();
                }
            } else {
                if (showCollection) {
                    titles = titleArray;
                    dialog = new WebViewMoreDialog.Builder(mContext, titles).build();
                } else {
                    titles = new String[]{"转发", "查看机构", "分享", "调整字号", "刷新", "复制链接", "浏览器打开"};
                    dialog = new WebViewMoreDialog.Builder(mContext, titles).build();
                }
            }
            dialog.setmListener(new WebViewMoreDialog.IOperateClickListener() {
                @Override
                public void clickListener(AdapterView<?> parent, View v, int position, long id) {
                    switch (titles[position]) {
                        case "收藏":
                            String msg_type;
                            if (type == MsgType.NOTICE.toNumber()) {
                                msg_type = Type.collectionFromType.FROM_NOTOCE;
                            } else if (type == MsgType.WNX_MSG.toNumber()) {
                                msg_type = Type.collectionFromType.FROM_WNX;
                            } else {
                                msg_type = Type.collectionFromType.FROM_HOME;
                            }
                            if (TextUtils.isEmpty(m_Web_Title)) {
                                T.showSingleL("网页还没加载完毕，请稍候");
                            } else {
                                Navigation.startCollectActivity(mContext, m_Web_Title, mUrl, org_id, msg_type, 0,
                                        msg_deptid);
                            }
                            break;
                        case "查看机构":
                            if (TextUtils.isEmpty(org_id)) {
                                T.showShort(mContext, "暂时无法查看");
                            } else {
                                BldNavigation.startOrgInfoActivity(mContext, org_id);
                            }
                            break;
                        case "调整字号":
                            changeSize();
                            break;
                        case "刷新":
                            webView.loadUrl(mUrl);
                            break;
                        case "转发":
                            BldNavigation.wnxMsgForward(mContext, mUrl, m_Web_Title);
                            break;
                        case "复制链接":
                            clipboard.setPrimaryClip(ClipData.newPlainText(null, (mUrl)));
                            T.showShort(mContext, R.string.content_copyed);
                            break;
                        case "分享":
//                            mContent = m_Web_Title + mUrl;
                            new ShareAction(getActivity()).setDisplayList(/*SHARE_MEDIA.SINA, SHARE_MEDIA.QQ,
                        SHARE_MEDIA.QZONE,SHARE_MEDIA.WEIXIN_FAVORITE,SHARE_MEDIA.MORE*/ SHARE_MEDIA.WEIXIN, SHARE_MEDIA
                                    .WEIXIN_CIRCLE, SHARE_MEDIA.EMAIL, SHARE_MEDIA.SMS)
                                    .withTitle(m_Web_Title)
                                    .withText(TextUtils.isEmpty(mContent) ? "12316云" +
                                            ".农业微门户系统，是基于云服务模式的的农业管理与服务的O2O解决方案。12316云门户APP是农民贴身的农技员和信息站。" : mContent)
//                            .withMedia(new UMImage(PlatformWebViewAct.this, "mediaUrl"))
                                    .withTargetUrl(mUrl)
                                    .setCallback(umShareListener)
                                    .open();
                            break;
                        case "浏览器打开":
                            Intent intent = new Intent();
                            intent.setAction("android.intent.action.VIEW");
                            Uri content_url = Uri.parse(mUrl);
                            intent.setData(content_url);
                            startActivity(intent);
                            break;
                    }
                }
            });
        }
        dialog.show();
    }

    WebChromeClient wcc = new WebChromeClient() {
        public void onReceivedTitle(WebView view, String title) {
            if (type == MsgType.NOTICE.toNumber() || type == MsgType.WNX_MSG.toNumber()) {
                mTitleBar.setTitle("资讯详情");
            } else {
//                mTitleBar.setTitle(title);
            }
        }
    };

    private void changeSize() {
        //调整字体
        if (setTextSize == null) {
            setTextSize = new DialogSetTextSize.Builder(mContext);
        }
        setTextSize.setIndex(index);
        setTextSize.setButtonText(R.string.cancel); //1.初始化按钮文字
        tempIndex = index;//1.初始化中转变量
        setTextSize.setListener(new DialogSetTextSize.ISeekbarListener() {
            @Override
            public void onProgressChanged(RangeSliderView rsv, int indexInner) {
                setTextSize.setButtonText(R.string.button_ok);
                tempIndex = indexInner; //2.当变量改变时,交由中转变量保存
                webView.getSettings().setTextZoom(50 + indexInner * 25);
            }
        }, new ButtonClickListener() {
            @Override
            public void buttonClick(View view) {
                if (index == tempIndex) { //没有变动,返回
                    return;
                } else { //发生了改变
                    index = tempIndex; //3.将新的index保存,修改大小
                    PreferencesUtils.SaveIntData(WEB_VIEW_INDEX, index);
                    webView.getSettings().setTextZoom(50 + index * 25);
                }
            }
        });
        setTextSize.setDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                LogUtil.d("wubaojie>>>onDismiss: dismiss");
            }
        });
        setTextSize.setCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                LogUtil.d("wubaojie>>>onCancel: cancel");
                webView.getSettings().setTextZoom(50 + index * 25);
            }
        });
        setTextSize.show();
    }

    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onResult(SHARE_MEDIA platform) {
            com.umeng.socialize.utils.Log.d("plat", "platform" + platform);
            if (platform.name().equals("WEIXIN_FAVORITE")) {
                Toast.makeText(mContext, platform + " 收藏成功啦", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(mContext, platform + " 分享成功啦", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(mContext, platform + " 分享失败啦", Toast.LENGTH_SHORT).show();
            if (t != null) {
                com.umeng.socialize.utils.Log.d("throw", "throw:" + t.getMessage());
            }
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(mContext, platform + " 分享取消了", Toast.LENGTH_SHORT).show();
        }
    };


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /** attention to this below ,must add this**/
        UMShareAPI.get(mContext).onActivityResult(requestCode, resultCode, data);
        com.umeng.socialize.utils.Log.d("result", "onActivityResult");
    }

    private RequestQueue mRequestQueue;
    private StringRequest mStringRequest;

    private void volleyGetShortUrl(String url_param) {
        if (TextUtils.isEmpty(url_param))
            return;
        LogUtil.d("wnx", "volley_get platform url_param:" + url_param);
        String url = "http://api.t.sina.com.cn/short_url/shorten.json?source=3213676317&url_long=" + url_param;
        // 1 创建RequestQueue对象
        mRequestQueue = Volley.newRequestQueue(mContext);
        // 2 创建StringRequest对象
        mStringRequest = new StringRequest(url, new Listener<String>() {
            @Override
            public void onResponse(String response) {
                LogUtil.v("wnx", "volleyGetShortUrl onResponse info:" + response);
                try {
                    JSONArray jsArr = new JSONArray(response);
                    JSONObject js = jsArr.getJSONObject(0);
                    String url_short = js.getString("url_short");
                    if (!TextUtils.isEmpty(url_short)) {
                        mUrl = url_short;
                    }
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }, new ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                LogUtil.v("exweb", "volleyGetShortUrl onErrorResponse info:" + error.toString());
            }

        });
        // 3 将StringRequest添加到RequestQueue
        mRequestQueue.add(mStringRequest);
    }
}
